package com.livace.doctool.pdf.application;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import com.livace.doctool.pdf.dto.PdfRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class PdfServiceImpl implements PdfService {

    // 添加按行提取PDF内容的方法
    @Override
    public Optional<String> generateByLingMa(MultipartFile file) {
        try {
            // 创建临时文件
            Path projectPath = Paths.get("").toAbsolutePath();
            Path tempDir = Files.createTempDirectory(projectPath, "pdf_split");
            File originalFile = new File(tempDir.toFile(), "original.pdf");
            file.transferTo(originalFile);
            String generatedFilePath = null;

            PdfDocument sourcePdf = new PdfDocument(new PdfReader(originalFile));

            int numberOfPages = sourcePdf.getNumberOfPages();
            List<String> chineseLines = new ArrayList<>(1000);
            String chineseId = "";
            boolean lastLineIsEnglish = false;
            for (int i = 1; i <= numberOfPages; i++) {
                System.out.println("Processing page " + i);
                // 按行提取文本内容
                List<String> lines = extractLinesFromPage(sourcePdf.getPage(i));
                for (String line : lines) {
                    if (line == null || line.isEmpty()) {
                        continue;
                    }
                    //序号
                    if (line.contains("、")) {
                        chineseId = line.substring(0, line.indexOf('、') + 1);
                        chineseId = chineseId.length() < 5 ? chineseId : "";
                    }
                    boolean chineseLine = extractChinese(line);

                    if (chineseLine) {
                        if (lastLineIsEnglish) {
                            line = chineseId + line;
                            lastLineIsEnglish = false;
                        }
                        chineseLines.add(line);
                    } else {
                        lastLineIsEnglish = true;
                    }
                }
            }
            if (!chineseLines.isEmpty()) {
                generatedFilePath = generateTextPdf(new PdfRequest(chineseLines));
                log.info("生成的pdf文件路径：{}", generatedFilePath);
            }
            sourcePdf.close();
            assert generatedFilePath != null;
            return Optional.of(generatedFilePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 添加按行提取PDF内容的方法
    private List<String> extractLinesFromPage(com.itextpdf.kernel.pdf.PdfPage page) {
        // 使用不同的策略提取文本
        com.itextpdf.kernel.pdf.canvas.parser.listener.LocationTextExtractionStrategy strategy =
                new com.itextpdf.kernel.pdf.canvas.parser.listener.LocationTextExtractionStrategy();

        String text = PdfTextExtractor.getTextFromPage(page, strategy);

        // 按行分割文本
        String[] lines = text.split("\\r?\\n");
        return new ArrayList<>(Arrays.asList(lines));
    }


    private boolean extractChinese(String text) {

        if (text.length() < 4) {
            return true;
        }

        boolean isChinese = false;
        // 使用更全面和准确的中文字符范围
        StringBuilder result = new StringBuilder();
        String ffWords = text.length() > 5 ? text.substring(0, 5) : text;

        for (int i = 0; i < ffWords.length(); i++) {
            char c = text.charAt(i);

            // 检查是否为中文字符（更全面的范围）
            if ((c >= 0x4e00 && c <= 0x9fff) ||     // CJK统一汉字
                    (c >= 0x3400 && c <= 0x4dbf) ||     // CJK扩展A
                    (c >= 0x20000 && c <= 0x2a6df) ||   // CJK扩展B
                    (c >= 0x2a700 && c <= 0x2b73f) ||   // CJK扩展C
                    (c >= 0x2b740 && c <= 0x2b81f) ||   // CJK扩展D
                    (c >= 0x2b820 && c <= 0x2ceaf) ||   // CJK扩展E
                    (c >= 0xf900 && c <= 0xfaff) ||     // CJK兼容汉字
                    (c >= 0x31c0 && c <= 0x31ef) ||     // CJK笔画
                    (c >= 0x2e80 && c <= 0x2eff) ||     // CJK部首补充
                    (c >= 0x2f00 && c <= 0x2fdf) ||     // 康熙部首
                    (c >= 0x3100 && c <= 0x312f) ||     // 注音符号
                    (c >= 0x31a0 && c <= 0x31bf)) {     // 注音符号扩展
                result.append(c);
            }
            // 保留中文标点符号
            else if ((c >= 0x3000 && c <= 0x303f) ||   // 中文标点符号
                    (c >= 0xff00 && c <= 0xffef) ||   // 全角ASCII、全角标点
                    c == '，' || c == '。' || c == '！' || c == '？' ||
                    c == '；' || c == '：' || c == '“' || c == '”' ||
                    c == '‘' || c == '’' || c == '（' || c == '）' ||
                    c == '【' || c == '】' || c == '《' || c == '》') {
                // 只有在已经有中文字符的情况下才添加标点
                if (!result.isEmpty()) {
                    result.append(c);
                }
            }
            // 处理空格和换行符
            else if (Character.isWhitespace(c) && !result.isEmpty()) {
                // 避免连续空格
                if (result.charAt(result.length() - 1) != ' ') {
                    result.append(' ');
                }
            }
        }
        if (result.length() > 1) {
            isChinese = true;
        }
        return isChinese;
    }


    @Override
    public String generateTextPdf(PdfRequest request) throws IOException {
        // 确保输出目录存在
        Path projectPath = Paths.get("").toAbsolutePath();
        Path outputDir = Files.createTempDirectory(projectPath, request.getOutputPath());
        if (!Files.exists(outputDir)) {
            Files.createDirectories(outputDir);
        }

        // 创建完整文件路径
        Path filePath = outputDir.resolve(request.getFilename());
        File outputFile = filePath.toFile();

        try (PdfWriter writer = new PdfWriter(outputFile);
             PdfDocument pdf = new PdfDocument(writer);
             Document document = new Document(pdf)) {

            // 创建中文字体
            PdfFont chineseFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H",
                    PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);

            // 设置页边距
            document.setMargins(50, 50, 50, 50);

            // 添加标题
            if (request.getTitle() != null && !request.getTitle().isEmpty()) {
                Paragraph title = new Paragraph(request.getTitle())
                        .setFont(chineseFont)
                        .setFontSize(16)
                        .setTextAlignment(TextAlignment.CENTER)
                        .setMarginBottom(10);
                document.add(title);
            }

            // 添加时间戳
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Paragraph timestampPara = new Paragraph("生成时间: " + timestamp)
                    .setFont(chineseFont)
                    .setFontSize(10)
                    .setTextAlignment(TextAlignment.RIGHT)
                    .setMarginBottom(20);
            document.add(timestampPara);

            // 添加分隔线
            document.add(new Paragraph("")
                    .setFixedPosition(50, document.getPdfDocument().getLastPage().getPageSize().getHeight() - 80,
                            document.getPdfDocument().getDefaultPageSize().getWidth() - 100)
                    .setHeight(0.5f)
                    .setMarginBottom(15));

            // 按行添加文本内容
            for (String line : request.getLines()) {
                Paragraph textLine = new Paragraph(line)
                        .setFont(chineseFont)
                        .setFontSize(request.getFontSize())
                        .setMarginBottom(5);
                document.add(textLine);
            }

            // 添加页脚
            String footerText = String.format("共 %d 行 | 第 %%d 页", request.getLines().size());
            document.showTextAligned(new Paragraph(footerText)
                            .setFont(chineseFont)
                            .setFontSize(8),
                    297.5f, 30, document.getPdfDocument().getNumberOfPages(),
                    TextAlignment.CENTER, null, 0);
        }

        return outputFile.getAbsolutePath();
    }
}
